<?php
declare (strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;

class UserSign extends Base
{
    public static function add($user, $system): array
    {
        parent::startTrans();
        try {
            if ($user->is_day_sign == 1) {
                throw new \Exception('您今天已经签到过了！');
            }
            $user->sign_day += 1;
            $user->always_day += 1;
            $user->is_day_sign = 1;
            $user->save();
            if ($system['sign_give'] > 0) {
                Target::Account()->basics($user->id, 'bonus', $system['sign_give'], '签到', '+')
                    ->createNormal();
            }
            parent::create([
                'uid' => $user->id,
                'give_amount' => $system['sign_give'],
                'create_date' => date('Y-m-d')
            ]);
            $content = "您签到成功，获得【{$system['sign_give']}】元";
            UserNotify::add(1, $user->id, '签到成功', $content);
            $result = [
                'always_day' => $user->always_day,
                'sign_day' => $user->sign_day,
                'amount' => $system['sign_give']
            ];
            parent::commit();

            return ['code' => 1, 'msg' => '签到成功', 'data' => $result];
        } catch (\Exception $e) {
            parent::rollback();

            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}